package com.seckill.listener;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seckill.mapper.VoucherOrderMapper;
import com.seckill.pojo.entity.VoucherOrder;
import com.seckill.service.SeckillCouponService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Component
@Transactional
public class VoucherOrderListener extends ServiceImpl<VoucherOrderMapper, VoucherOrder> {
    @Autowired
    SeckillCouponService seckillCouponService;
    @Resource
    private RedissonClient redissonClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sky.voucherOrder.pay.queue",durable = "true"),
            exchange = @Exchange(name = "voucherOrder.pay.topic",type = ExchangeTypes.TOPIC),
            key = "voucherOrder.pay.success"
    ))
    public void listenedOrder(VoucherOrder voucherOrder) {
        handleVocherOrder(voucherOrder);
    }
    //处理订单
    private void handleVocherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();//失败不等待
        //获取锁失败则抛出异常
        if(!isLock){
            log.error("获取锁失败");
            return;
        }
        try {
            createVoucher(voucherOrder);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    //下单功能提取出来
    public void createVoucher(VoucherOrder voucherOrder) {
        //一人一单功能  如果能在订单表中查到商品id和用户id
        Long UserId=voucherOrder.getUserId();
        Integer count = query().eq("user_id", UserId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count>0){

            log.error("该用户已经购买");
            return;
        }
        //扣减库存
        boolean success =seckillCouponService.decStock(voucherOrder.getVoucherId());
        if(!success){

            log.error("库存不足");
            return;
        }
        save(voucherOrder);
        //throw new RuntimeException("测试事务回滚");
    }
}
